const webpack = require('atool-build/lib/webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const TypedocWebpackPlugin = require('typedoc-webpack-plugin');

const _ = require('lodash');

module.exports = function (webpackConfig, env) {
  return [config(_.cloneDeep(webpackConfig), env),
    config(_.cloneDeep(webpackConfig), env, true)]
}

function config(webpackConfig, env, isRender) {
  // webpackConfig.babel.plugins.push('transform-runtime');
  // 服务器渲染的特殊配置
  if (isRender) {
    webpackConfig.entry = {
      "render": "./render/index.ts"
    };
    webpackConfig.target = 'node';
  }
  // console.log(webpackConfig.babel.plugins);
  // Support hmr
  if (env === 'development') {
    webpackConfig.devtool = '#eval';
    webpackConfig.babel.plugins.push('dva-hmr');
  } else {
    webpackConfig.babel.plugins.push('dev-expression');
  }

  // Don't extract common.js and common.css
  webpackConfig.plugins = webpackConfig.plugins.filter(function (plugin) {
    return !(plugin instanceof webpack.optimize.CommonsChunkPlugin);
  });

  // Support CSS Modules
  // Parse all less files as css module.
  webpackConfig.module.loaders.forEach(function (loader, index) {
    if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.less$') > -1) {
      loader.include = /node_modules/;
      loader.test = /\.less$/;
    }
    if (loader.test.toString() === '/\\.module\\.less$/') {
      loader.exclude = /node_modules/;
      loader.test = /\.less$/;
    }
    if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.css$') > -1) {
      loader.include = /node_modules/;
      loader.test = /\.css$/;
    }
    if (loader.test.toString() === '/\\.module\\.css$/') {
      loader.exclude = /node_modules/;
      loader.test = /\.css$/;
    }
  });

  // webpackConfig.babel.plugins.push(['import', [
  //   {
  //     libraryName: 'antd',
  //     style: 'css',
  //   },
  // ]]);

  // copy assets to dist
  webpackConfig.plugins.push(new CopyWebpackPlugin([
    { from: 'src/assets' }
  ]));
  // typedoc
  webpackConfig.plugins.push(new TypedocWebpackPlugin({
    out: '../doc/typedoc',
    module: 'commonjs',
    target: 'es6',
    mode: 'modules',
    includeDeclarations: false,
    ignoreCompilerErrors: true,
    excludePrivate: false,
    exclude: '**/node_modules|.history)/**/*.*',
  }, ['./render', './src']));

  // console.log(webpackConfig.babel.plugins);
  return webpackConfig;
};
